package com.lemonPiggy.UDForm.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lemonPiggy.UDForm.domain.UDFormAuthorize;
import com.lemonPiggy.UDForm.domain.UDFormField;
import com.lemonPiggy.UDForm.domain.UDFormWebPage;
import com.lemonPiggy.UDForm.service.IUDFormAuthorizeService;
import com.lemonPiggy.UDForm.service.IUDFormWebPageService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.api.RemoteRoleService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.PreAuthorize;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 页面自定义Controller
 *
 * @author ruoyi
 * @date 2021-08-02
 */
@RestController
@RequestMapping("/page")
public class UDFormWebPageController extends BaseController
{
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IUDFormWebPageService UDFormWebPageService;
    @Autowired
    IUDFormAuthorizeService UDFormAuthorizeService;
    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    RemoteRoleService remoteRoleService;
    /**
     * 查询页面自定义列表
     */
    @PreAuthorize(hasPermi = "lemonPiggy-UDForm:page:list")
    @GetMapping("/list")
    public TableDataInfo list(UDFormWebPage UDFormWebPage)
    {
        startPage();
        List<String> list1 = new ArrayList<>();
        List<UDFormWebPage> list = UDFormWebPageService.selectUDFormWebPageList(UDFormWebPage);
        for (UDFormWebPage diyWebPage : list) {
            String pageId = diyWebPage.getId();
            List<UDFormAuthorize> UDFormAuthorizes = UDFormAuthorizeService.selectTypeId(pageId);
            String userName = "用户:";
            String roleName = "角色:";
            Map<String,List<String>> gmap=new HashMap<>();
            gmap.put("1",new ArrayList<>());
            gmap.put("2",new ArrayList<>());
            for(int i = 0; i< UDFormAuthorizes.size(); i++){
                gmap.get(UDFormAuthorizes.get(i).getAuthorizeType()).add(UDFormAuthorizes.get(i).getAuthorizeId());
            }
//            for(String key:gmap.keySet()){
                for(String id:gmap.get("1")){
                    SysUser sysUser = remoteUserService.getUserInfoById(Long.valueOf(id)).getData().getSysUser();
                    userName=userName+sysUser.getUserName()+",";
                }
                for(String id:gmap.get("2")){
                    SysRole data = remoteRoleService.selectId(Long.valueOf(id)).getData();
                    roleName=roleName+data.getRoleName()+",";
                }

//            }
                if (UDFormAuthorizes.size()==0) {
                    diyWebPage.setAuthorizeType("没有绑定权限!");
                }else{
                    diyWebPage.setAuthorizeType(userName+roleName);
                }
        }
        return getDataTable(list);
    }
    //不带分页的查询所有表单接口
    @GetMapping("/listAll")
    public R list1(UDFormWebPage UDFormWebPage)
    {
        List<UDFormWebPage> list = UDFormWebPageService.selectUDFormWebPageList(UDFormWebPage);
        return R.ok(list);
    }

    /**
     * 导出页面自定义列表
     */
    @PreAuthorize(hasPermi = "lemonPiggy-UDForm:page:export")
    @Log(title = "页面自定义", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UDFormWebPage UDFormWebPage) throws IOException
    {
        List<UDFormWebPage> list = UDFormWebPageService.selectUDFormWebPageList(UDFormWebPage);
        ExcelUtil<UDFormWebPage> util = new ExcelUtil<UDFormWebPage>(UDFormWebPage.class);
        util.exportExcel(response, list, "页面自定义数据");
    }

    /**
     * 获取页面自定义详细信息
     */
//    @PreAuthorize(hasPermi = "lemonPiggy-UDForm:page:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        UDFormWebPage UDFormWebPage = UDFormWebPageService.selectUDFormWebPageById(id);
        List<UDFormAuthorize> UDFormAuthorizes = UDFormAuthorizeService.selectTypeId(id);
        List<String> list = new ArrayList<>();
        String userName = null;
        String roleName = null;
        List<Long> list2 = new ArrayList<>();
        List<Long> list3  = new ArrayList<>();
        for (UDFormAuthorize UDFormAuthorize : UDFormAuthorizes) {
            String authorizeId = UDFormAuthorize.getAuthorizeId();
            String authorizeType = UDFormAuthorize.getAuthorizeType();
            if (authorizeType.equals("1")) {
                SysUser sysUser = remoteUserService.getUserInfoById(Long.valueOf(authorizeId)).getData().getSysUser();
                userName = "用户:"+sysUser.getUserName();
                list.add(userName);
            }
            if (authorizeType.equals("2")) {
                SysRole data = remoteRoleService.selectId(Long.valueOf(authorizeId)).getData();
                roleName = "角色:"+ data.getRoleName();
                list.add(roleName);
            }
            String join = StringUtils.join(list, ",");
            UDFormWebPage.setAuthorizeType(join);
            Long userId = SecurityUtils.getUserId();
        }
        List<UDFormField> fieldList1 = UDFormWebPage.getFieldList();
        String relationShip = UDFormWebPage.getRelationShip();
        if (relationShip !=null) {
            JSONObject jsonObject = JSON.parseObject(relationShip);
            String page = jsonObject.getString("page");
            UDFormWebPage UDFormWebPage1 = UDFormWebPageService.selectUDFormWebPageById(page);
            List<UDFormField> fieldList = UDFormWebPage1.getFieldList();
            fieldList1.addAll(fieldList);
        }
        return AjaxResult.success(UDFormWebPage);
    }

    /**
     * 新增页面自定义
     */
    @PreAuthorize(hasPermi = "lemonPiggy-UDForm:page:add")
    @Log(title = "页面自定义", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Valid UDFormWebPage UDFormWebPage)
    {
        return toAjax(UDFormWebPageService.insertUDFormWebPage(UDFormWebPage));
    }

    /**
     * 修改页面自定义
     */
    @PreAuthorize(hasPermi = "lemonPiggy-UDForm:page:edit")
    @Log(title = "页面自定义", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UDFormWebPage UDFormWebPage)
    {
        return toAjax(UDFormWebPageService.updateUDFormWebPage(UDFormWebPage));
    }

    /**
     * 删除页面自定义
     */
    @PreAuthorize(hasPermi = "lemonPiggy-UDForm:page:remove")
    @Log(title = "页面自定义", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(UDFormWebPageService.deleteUDFormWebPageByIds(ids));
    }

    //查询应用，入参为map
    @GetMapping("/optionselect/{appId}")
    public R<List<Map<String,Object>>> optionselect (@PathVariable("appId") String appId){
        List<Map<String, Object>> map = UDFormWebPageService.optionselect(appId);
        return R.ok(map);
    }
    //表关联页面的更新
    @PutMapping("/update")
    public AjaxResult update(@RequestBody UDFormWebPage UDFormWebPage){
        return toAjax(UDFormWebPageService.updatePage(UDFormWebPage));
    }

    @GetMapping("/test")
    public R selectTest(UDFormWebPage UDFormWebPage){
        List<UDFormWebPage> list = UDFormWebPageService.selectUDFormWebPageList(UDFormWebPage);
        for (UDFormWebPage diyWebPage : list) {
            if (diyWebPage.getAuthorizeType()!=null){
                if (diyWebPage.getAuthorizeType().equals("2")) {
                    String authorizeId = diyWebPage.getAuthorizeId();
                    SysRole sysRoleR = remoteRoleService.selectId(Long.valueOf(authorizeId)).getData();
                    System.out.println(sysRoleR + "------------");
                    diyWebPage.setAuthorizeType(sysRoleR+"");
                }
            }
        }
        return R.ok(list);
        }
}
